package edu.sandau.f210153.f21010108.Controller;

import edu.sandau.f210153.f21010108.model.Product;
import edu.sandau.f210153.f21010108.repository.ProductRepository;
import edu.sandau.f210153.f21010108.service.ProductService;
import jakarta.persistence.EntityNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Controller
public class ProductController {
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private ProductService productService ;
    @RequestMapping("product")
    public String getProduct(ModelMap map,Product product){
        if (StringUtils.isEmpty(product.getPrice())){
            product .setPrice(null);
        }
        if (StringUtils.isEmpty(product.getName())){
            product.setName(null);
        }
        map.put("products",productService .getAll(product));
        return "list";
    }
    @RequestMapping("product/delete/{id}")
    public String delete(@PathVariable Long id){
        productService.delete(id);
        return "redirect:/product";
    }

    @RequestMapping("product/create")
    public String create(){

        return "create";
    }
    @RequestMapping("product/save")
    public String save(@RequestParam String name,@RequestParam String price){
        Product s = new Product();
        s.setName(name);
        s.setPrice(price);
        productService.save(s);
        return "redirect:/product";
    }
    @RequestMapping("product/update/{id}")
    public String update(ModelMap map,@PathVariable Long id){
        map.put("product",productService.get(id));
        return "update";
    }
    @RequestMapping("product/edit")
    public String edit(Product product) {
        productService.save(product);
        return "redirect:/product";
    }
}
